<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的saas管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.niucloud-admin.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------

namespace app\api\service\weapp;

use app\api\service\login\LoginService;
use app\api\service\login\RegisterService;
use app\api\service\member\MemberService;
use app\core\base\BaseApiService;
use app\core\exception\ApiException;
use app\core\exception\AuthException;
use app\dict\member\MemberLoginTypeDict;
use app\dict\member\MemberRegisterTypeDict;
use app\service\core\weapp\CoreWeappAuthService;
use app\service\core\weapp\CoreWeappService;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


/**
 * 微信配置模型
 * Class WechatConfigService
 * @package app\service\core\wechat
 */
class WeappAuthService extends BaseApiService
{

     public $core_weapp_serve_service;

     public function __construct()
     {
          parent::__construct();
          $this->core_weapp_serve_service = new CoreWeappAuthService();
     }

     /**
      * 通过code获取微信小程序用户信息
      * @param string $code
      * @return array
      * @throws InvalidConfigException
      */
     public function getUserInfoByCode(string $code)
     {
//        $iv = $this->request->param('iv', '');
//        $encrypted_data = $this->request->param('encrypted_data', '');
          $result = $this->core_weapp_serve_service->session($code);
//        if(empty($result)) throw new ApiException('WECHAT_EMPOWER_NOT_EXIST');
//          $userinfo = $this->core_weapp_serve_service->decryptData($result['session_key'], $iv, $encrypted_data);
          $openid = $result['openid'] ?? '';//对应微信的 openid
          $unionid = $result['unionid'] ?? '';//对应微信的 unionid
          if (empty($openid)) throw new ApiException('WECHAT_EMPOWER_NOT_EXIST');
          //todo 这儿还可能会获取用户昵称 头像  性别 ....用以更新会员信息
//        $nickname = $userinfo['nickName'] ?? '';//对应微信的 nickname
//        $avatar = $userinfo['avatarUrl'] ?? '';//对应微信的 头像地址
//        $sex = $userinfo['gender'];//性别
          return [
               $openid,
               $unionid,
//            $avatar,
//            $nickname,
//            $sex
          ];
     }

     /**
      * 登录
      * @param string $code
      * @return array
      */
     public function login(string $code)
     {

          [
               $openid,
               $unionid,
//            $avatar,
//            $nickname,
//            $sex
          ] = $this->getUserInfoByCode($code);
          $member_service = new MemberService();
          $member_info = $member_service->findMemberInfo(['weapp_openid' => $openid]);
          if(empty($member_info['mobile'])){
               $is_need_phone_number = 1;
               return [
                    'id' => $member_info['member_id'],
                    'openid' => $openid,
                    'is_need_phone_number' => $is_need_phone_number,
                    'token' => $token_info['token']??'',
                    'expires_time' => $token_info['expires_time']??'',
               ];
          }else{
               //可能会更新用户和粉丝表
               $login_service = new LoginService();
               return $login_service->login($member_info, MemberLoginTypeDict::WEAPP);
          }

     }

     /**
      * 注册
      * @param string $openid
      * @param string $mobile
      * @param string $mobile_code
      * @return array
      * @throws DataNotFoundException
      * @throws DbException
      * @throws GuzzleException
      * @throws InvalidConfigException
      * @throws ModelNotFoundException
      */
     public function register(string $openid, string $mobile = '', string $mobile_code = '')
     {
          $this->mobile($mobile_code);
          if (empty($openid)) throw new AuthException('AUTH_LOGIN_TAG_NOT_EXIST');
          //todo openid可能还需要合法性验证
          if (empty($mobile)) {
               $result = $this->core_weapp_serve_service->getUserPhoneNumber($mobile_code);
               if (empty($result)) throw new ApiException('WECHAT_EMPOWER_NOT_EXIST');
               $phone_info = $result['phone_info'];
               $mobile = $phone_info['purePhoneNumber'];
               if (empty($mobile)) throw new ApiException('WECHAT_EMPOWER_NOT_EXIST');
               $is_verify_mobile = false;
          } else {
               $is_verify_mobile = true;
          }
          $member_service = new MemberService();
          $member_info = $member_service->findMemberInfo(['weapp_openid' => $openid]);

          if (!$member_info->isEmpty()) throw new AuthException('MEMBER_IS_EXIST');//账号已存在, 不能在注册
          $register_service = new RegisterService();
          return $register_service->register($mobile ?? '',
               [
                    'weapp_openid' => $openid
               ],
               MemberRegisterTypeDict::WEAPP,
               $is_verify_mobile ?? false
          );

     }

     //微信获取access_token
     public function getAccessToken($mobile_code)
     {
          $getAccessToken = $this->core_weapp_serve_service->getUserPhoneNumber($mobile_code);
          return $getAccessToken;
     }

     public function mobile(string $code)
     {
          $api = CoreWeappService::appApiClient();
          return $api->postJson('wxa/business/getuserphonenumber', [
               'code' => (string)$code,
          ]);
     }

}
